/*
 * @(#)Snapshot.java
 *
 */

package diablo3;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import diablo3.simulate.Keyboard;

public class Snapshot {
	
	public static final String SAVE_PATH = "F:";
	public static final String SAVE_FORMAT = "jpg";
	private static final Log LOG = LogFactory.getLog(Snapshot.class);
	
	/**
	 * 按键截屏
	 * @param keyEnvent 传入截屏按键
	 * @param path 截屏保存路径
	 * @throws AWTException
	 */
	public String snapshot(String key , String path){
		if(key == null || key.trim().equals("")){
			return null;
		}
		key = key.trim();
		Keyboard keyboard = new Keyboard();
		if(key.startsWith(Keyboard.SPECIAL_FLAG)){
			keyboard.typeSpecial(key);
		}
		else {
			keyboard.type(key);
		}
		
		try {
			//等待生成图片
			Thread.sleep(10 * 1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		File file = new File(path);
		if(!file.isDirectory()){
			throw new IllegalArgumentException("worng path ：不是目录路径 " + path);
		}
		File latestImage = null; 
		for(File image : file.listFiles()){
			if(latestImage == null || 
					image.lastModified() > latestImage.lastModified()){
				latestImage = image;
			}
		}
		
		return latestImage.getAbsolutePath();
	}
	
	/**
	 * 截屏保存
	 * @param bufferedImage
	 * @return
	 */
	public String saveToFile(BufferedImage bufferedImage) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
		String name = sdf.format(new Date());
		File path = new File(SAVE_PATH);
		String format = SAVE_FORMAT;
		File f = new File(path + File.separator + name + "." + format);
		try {
			ImageIO.write(bufferedImage, format, f);
		} catch (IOException e) {
			LOG.error(e.getMessage(),e);
		}
		return name;
	}

	/**
	 * java API 截屏
	 * @return
	 */
	public BufferedImage snapshot() {
		BufferedImage image = null;
		try {
			Robot robot = new Robot();
			Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
			image = robot.createScreenCapture(new Rectangle(0, 0, d.width,
					d.height));
		} catch (AWTException e) {
			e.printStackTrace();
		}
		return image;
	}
	
	public void deleteScreenShot(String fileNamePath){
		File file = new File(fileNamePath);
		if(file.exists()){
			file.delete();
		}
	}
	
	/**
	 * 全屏截屏
	 * @return
	 */
	public String screenShot(){
		Snapshot snapshot = new Snapshot();
		String name = snapshot.saveToFile(snapshot.snapshot());
		return Snapshot.SAVE_PATH + File.separator + name + "." + Snapshot.SAVE_FORMAT;
	}
}